package com.lanou.sfu.songforu.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.base.BaseAcitvity;
import com.lanou.sfu.songforu.datas.MusicListDatas;
import com.lanou.sfu.songforu.lrc.LyricAdapter;
import com.lanou.sfu.songforu.lrc.LyricDownloadManager;
import com.lanou.sfu.songforu.lrc.LyricLoadHelper;
import com.lanou.sfu.songforu.lrc.LyricSentence;
import com.lanou.sfu.songforu.lrc.MusicApp;
import com.lanou.sfu.songforu.view.MusicInterface;
import com.lanou.sfu.songforu.view.MusicPopuoWindow;
import com.lanou.sfu.songforu.service.PlayerService;
import com.lanou.sfu.songforu.view.Time;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by quyan on 15/11/5.
 */
public class PlayerQueueActivity extends BaseAcitvity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private static ImageView upBtn, playBtn, nextBtn, play_list, play_static;
    private static TextView main_play_songName, main_singerName;
    private static SeekBar seekBar;//进度条
    private static MusicInterface musicService;
    private Timer timer;
    private MusicPopuoWindow musicPopuoWindow;
    private static TextView timeStart, timeEnd;
    private ArrayList<MusicListDatas> listDatases;
    private boolean isDestory = false;
    private int typeId;
    private static final String modeName[] = {"列表循环", "顺序播放", "随机播放", "单曲循环"};
    private int modeDrawable[] = {R.mipmap.img_appwidget_playmode_repeat,
            R.mipmap.img_appwidget_playmode_sequence, R.mipmap.img_appwidget_playmode_shuffle,
            R.mipmap.img_appwidget_playmode_repeatone};

    private int mScreenWidth;
    private ListView mListView;

    private LyricDownloadManager mLyricDownloadManager;
    private LyricLoadHelper mLyricLoadHelper;
    private TextView mLrcEmptyView;

    private LyricAdapter mLyricAdapter;

    /**
     * 歌词是否正在下载
     */
    private boolean mIsLyricDownloading;

    private ImageView main_play_back;

    //构建服务对象
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("xxx", "连接成功");
            musicService = (MusicInterface) service;
            loadLyricByHand(musicService.getName(), musicService.getUrl());
            if (timer == null) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Message message = handler.obtainMessage();
                        handler.sendMessage(message);
                    }
                }, 0, 500);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playqueue);
        mLyricDownloadManager = new LyricDownloadManager();
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricAdapter = new LyricAdapter(this);
        mLyricLoadHelper.setLyricListener(mLyricListener);
        //播放按钮
        upBtn = (ImageView) findViewById(R.id.upBtn);
        playBtn = (ImageView) findViewById(R.id.playBtn);
        nextBtn = (ImageView) findViewById(R.id.nextBtn);
        upBtn.setOnClickListener(this);
        playBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);

        //歌名作者名
        main_singerName = (TextView) findViewById(R.id.main_singerName);
        main_play_songName = (TextView) findViewById(R.id.main_play_songName);

        //时间
        timeStart = (TextView) findViewById(R.id.current_time);
        timeEnd = (TextView) findViewById(R.id.max_time);

        //列表
        play_list = (ImageView) findViewById(R.id.play_list);
        play_list.setOnClickListener(this);

        //循环模式
        play_static = (ImageView) findViewById(R.id.play_static);
        play_static.setOnClickListener(this);

        //取出保存的数据
        SharedPreferences sharedPreferences = getSharedPreferences("mode", MODE_PRIVATE);
        typeId = sharedPreferences.getInt("mode", 0);
        Picasso.with(this).load(modeDrawable[typeId]).into(play_static);
        EventBus.getDefault().post(typeId);


        //初始化listview
        mListView = (ListView) findViewById(R.id.lyricShow);
        mLrcEmptyView = (TextView) findViewById(R.id.lyric_empty);
        mListView.setEmptyView(mLrcEmptyView);
        mListView.setAdapter(mLyricAdapter);

        main_play_back = (ImageView) findViewById(R.id.main_play_back);
        main_play_back.setOnClickListener(this);

        DisplayMetrics metric = new DisplayMetrics();
        PlayerQueueActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;

        //进度条
        seekBar = (SeekBar) findViewById(R.id.play_seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    handler.removeMessages(1);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //拖动改变歌曲播放状态
                int progress = seekBar.getProgress();
                handler.sendEmptyMessage(1);
                //改变进度
                musicService.seekTo(progress);
            }
        });

        //绑定 开启 服务
        Intent intent = new Intent(this, PlayerService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playBtn://播放
                if (musicService.getIsPlay()) {
                    musicService.pause();
                } else if (musicService.getIsPlay() == false && musicService.getDuration() > musicService.getProgress()) {
                    musicService.continuePlay();
                }
                break;
            case R.id.nextBtn://下一曲
                musicService.next();
                break;
            case R.id.upBtn://上一曲
                musicService.upSong();
                break;
            case R.id.play_list:
                listDatases = musicService.musicList();
                musicPopuoWindow = new MusicPopuoWindow(musicService, this, listDatases);
                //显示窗口
                musicPopuoWindow.showAtLocation(PlayerQueueActivity.this.findViewById(R.id.play_liner),
                        Gravity.RIGHT, 0, 102); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.play_static:
                if (typeId < 3) {
                    typeId++;
                } else {
                    typeId = 0;
                }
                play_static.setImageResource(modeDrawable[typeId]);
                musicService.playMode(typeId);
                break;
            case R.id.lyric_empty:
                break;
            case R.id.main_play_back:
                finish();
                break;
        }

    }

    //静态方法 用来传值
    public static void play(ArrayList<MusicListDatas> lists, int position) {
        musicService.play(lists, position);
    }

    //不断获得当前进度的方法
    public  Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int duration = musicService.getDuration();//最大时长
            int currentPosition = musicService.getProgress();//当前播放时长
            //刷新进度条
            seekBar.setMax(duration);
            seekBar.setProgress(currentPosition);
            //转换时间格式
            timeStart.setText(Time.formatTime((long) currentPosition));
            timeEnd.setText(Time.formatTime((long) duration));
            //改变按钮状态
            if (musicService.getIsPlay()) {
                playBtn.setImageResource(R.mipmap.img_appwidget_pause);
            } else {
                playBtn.setImageResource(R.mipmap.img_appwidget_play);
            }
            //设置歌曲名 作者名
            main_play_songName.setText(musicService.getName());
            main_singerName.setText(musicService.getSinger());
            mLyricLoadHelper.notifyTime((long)currentPosition);
            return false;
        }
    });


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestory = true;
        unbindService(connection);//解绑服务
        SharedPreferences sharedPreferences = getSharedPreferences("mode", MODE_PRIVATE);//获得sharedPreferences对象
        SharedPreferences.Editor editor = sharedPreferences.edit();//通过sharedPreferences接口获得Edit对象
        editor.putInt("mode", typeId);//保存数据
        editor.commit();//提交
        editor.clear();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }



    private void loadLyricByHand(String musicName, String url) {
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = MusicApp.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            // Log.i(TAG, "loadLyric()--->本地有歌词，直接读取");
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            // Log.i(TAG, "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTask().execute(musicName, url);

        }
    }
    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = mLyricDownloadManager.fetchLyricContent(
                    params[0], params[1]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;
            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
            // Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            // 读取保存到本地的歌曲
            mLyricLoadHelper.loadLyric(result);
        }
    }
    public LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            // Log.i(TAG, "onLyricLoaded");
            if (lyricSentences != null) {
                // Log.i(TAG, "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
                // + ",当前句子索引=" + index);
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
                // mHandler.sendMessageDelayed(
                // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
                // 100);
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            // Log.i(TAG, "onLyricSentenceChanged--->当前句子索引=" +
            // indexOfCurSentence);
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            mListView.smoothScrollToPositionFromTop(indexOfCurSentence,
                    mListView.getHeight() / 2, 500);
        }
    };
}
